//
//  AppDelegate.m
//  cherryproduct
//
//  Created by umessage on 14-8-4.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "AppDelegate.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "UMSocial.h"
#import "WeiboSDK.h"
#import "UMSocialSinaHandler.h"


@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    _window.backgroundColor = [UIColor whiteColor];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    //是否显示statusbar  ActivityIndicator（AFNetworking）
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    //显示主页
    _homeViewController = [[CPHomeViewController alloc] init];
    _navigationCongtroller = [[UINavigationController alloc] initWithRootViewController:_homeViewController];
    
    self.window.rootViewController = _navigationCongtroller;
    
    [UMSocialData setAppKey:@"53fc9df6fd98c5c9a0009069"];//UmengAppkey];//zsg的:540e632d56240b854a000be1
    
    [UMSocialWechatHandler setWXAppId:@"wx42bae2a079770c21"
                            appSecret:@"85762a1a96144f320249c0e3416074fe"
                                  url:@"http://www.weibo.com/2029912903/B3ogzA3p6"];
    
    //新浪微博
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    [WeiboSDK enableDebugMode:NO];
    [WeiboSDK registerApp:@"2579954416"];
    
    [_window makeKeyAndVisible];
    
    //loadingView
    UIView* loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_BOUNDS_WIDTH, DEVICE_BOUNDS_HEIGHT)];
    loadingView.backgroundColor = [UIColor redColor];//[UIColor colorWithRed:251.0/255.0 green:251.0/255.0 blue:248.0/255.0 alpha:0.8];
    
    
    loadingView.hidden = YES;
    loadingView.tag = 1212;
    UIImageView * view = [[UIImageView alloc] initWithFrame:CGRectMake(DEVICE_BOUNDS_WIDTH/2-133/2, DEVICE_BOUNDS_HEIGHT/2-60/2, 133, 58)];
    view.image = [UIImage imageNamed:@"loading"];
//    view.backgroundColor = [UIColor blackColor];
//    view.alpha = 0.8f;
//    view.layer.cornerRadius = 10;
    [loadingView addSubview:view];
    
    
    UIActivityIndicatorView* activity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];//指定进度轮的大小
    [activity setCenter:CGPointMake(DEVICE_BOUNDS_WIDTH/2, DEVICE_BOUNDS_HEIGHT/2-60/2+13)];//指定进度轮中心点
    activity.tag = 1100;
    [activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];//设置进度轮显示类型
    [loadingView addSubview:activity];
    
//    UIButton* cancelButton = [[UIButton alloc] initWithCommonParametersAndTarget:CGRectMake(DEVICE_BOUNDS_WIDTH/2-160/2+147,DEVICE_BOUNDS_HEIGHT/2-60/2 -10-64, [UIImage imageNamed:@"layer_hud_close.png"].size.width, [UIImage imageNamed:@"layer_hud_close.png"].size.height) backGroundImage:[UIImage imageNamed:@"layer_hud_close.png"] target:_sharedClient action:@selector(cancelButtonAction:)];
//    [loadingView addSubview:cancelButton];
    
    [[UIApplication sharedApplication].keyWindow addSubview:loadingView];
    
    //JPush
    {
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            //可以添加自定义categories
            [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                           UIUserNotificationTypeSound |
                                                           UIUserNotificationTypeAlert)
                                               categories:nil];
            //[[UIApplication sharedApplication] registerForRemoteNotifications];
        } else {
            //categories 必须为nil
            [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                           UIRemoteNotificationTypeSound |
                                                           UIRemoteNotificationTypeAlert)
                                               categories:nil];
#else
            //categories 必须为nil
            [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                           UIRemoteNotificationTypeSound |
                                                           UIRemoteNotificationTypeAlert)
                                               categories:nil];
#endif
            // Required
            [APService setupWithOption:launchOptions];
        }
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        //[APService setDebugMode];
        [APService setLogOFF];
    }
    //友盟统计
    {
        [MobClick setLogEnabled:NO];
        
        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        [MobClick setAppVersion:version];
        
        [MobClick startWithAppkey:@"53fc9df6fd98c5c9a0009069"
                     reportPolicy:BATCH
                        channelId:nil];
    }

    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    //return [TencentOAuth HandleOpenURL:url];
    
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result) {
        return YES;
    } else {
        result = [TencentOAuth HandleOpenURL:url];
        if (result) {
            return YES;
        } else {
            return [WeiboSDK handleOpenURL:url delegate:self];
        }
    }
}

//qq:联合登录
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        result = [TencentOAuth HandleOpenURL:url];
        
        if (result == FALSE) {
            return [WeiboSDK handleOpenURL:url delegate:self];
        }
        
        return result;
    }
    return result;
}
//新浪微博:

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    if ([request isKindOfClass:WBProvideMessageForWeiboRequest.class])
    {
//        ProvideMessageForWeiboViewController *controller = [[[ProvideMessageForWeiboViewController alloc] init] autorelease];
//        [self.viewController presentModalViewController:controller animated:YES];
    }
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *title = @"发送结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",(int)response.statusCode, response.userInfo, response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSLog(@"weibo userID:%@", [(WBAuthorizeResponse *)response userID]);
        NSLog(@"weibo token:%@", [(WBAuthorizeResponse *)response accessToken]);
        NSLog(@"weibo info:%@", response.userInfo);
        
        NSInteger a = [_navigationCongtroller.viewControllers count]-1;
        if (a >= 0) {
            id vc = [_navigationCongtroller.viewControllers objectAtIndex:a];
            if ([vc isKindOfClass:[LoginViewController class]]) {
                LoginViewController * l_vc = (LoginViewController*)vc;
                [l_vc joinLoginWeibo:response];
            }
        }
        
        /*
        NSString *title = @"认证结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\nresponse.userId: %@\nresponse.accessToken: %@\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",(int)response.statusCode,
                             [(WBAuthorizeResponse *)response userID],
                             [(WBAuthorizeResponse *)response accessToken],
                             response.userInfo,
                             response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        
        [alert show];
        */
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//    if (self.homeViewController) {
//        NSString * str_bb = self.homeViewController.str_update_url;
//        
//        if (str_bb != nil &&
//            [str_bb isKindOfClass:[NSString class]] &&
//            ![str_bb isEqualToString:@""]) {
//            
//            UIApplication * application = [UIApplication sharedApplication];
//            [application openURL:[NSURL URLWithString:str_bb]];
//        }
//    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//jpush

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // Required
    [APService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // Required
    [APService handleRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    NSInteger type = [[userInfo objectForKey:@"type"] integerValue];
    if (type == 0) {
        
    } else if (type == 1) {
        //团购页面
        NSString * str_group_id = [userInfo objectForKey:@"groupon_id"];
        
        if (self.homeViewController) {
            [self.homeViewController.navigationController popToRootViewControllerAnimated:NO];
            [self.homeViewController pushGoPage:str_group_id];
        }
    }
}


@end












